package com.qen.sheji.zhuanshiqi;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterInputStream;

/**
 * 在写入文件之前，对写入的字符进行压缩
 * 在读取文件的字符之后 ，对读取的字符进行解压
 */
public class CompressionFileReaderWriter implements ReaderWriter {

    private ReaderWriter readerWriter;

    public CompressionFileReaderWriter(ReaderWriter readerWriter) {
        this.readerWriter = readerWriter;
    }

    @Override
    public String read() {
        return decompress(readerWriter.read());
    }

    @Override
    public void write(String content) {
        readerWriter.write(compress(content));
    }

    private String compress(String strData) {
        var data = strData.getBytes();
        var bout = new ByteArrayOutputStream(512);
        var dos = new DeflaterOutputStream(bout, new Deflater());
        try {
            dos.write(data);
            dos.close();
            bout.close();
            return Base64.getEncoder().encodeToString(bout.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private String decompress(String strData) {
        var data = Base64.getDecoder().decode(strData);
        var in = new ByteArrayInputStream(data);
        var iin = new InflaterInputStream(in);
        var bout = new ByteArrayOutputStream(512);
        try {
            int b = 0;
            while ((b = iin.read()) != -1) {
                bout.write(b);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new String(bout.toByteArray());
    }
}
